package com.hyq.market.api;

import android.net.Uri;
import android.text.TextUtils;

import org.xutils.http.body.RequestBody;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/28 0028.
 */

public class UrlEncodedParamsBody implements RequestBody {

    private byte[] content;
    private String charset = "UTF-8";

    public UrlEncodedParamsBody(Map<String,String> map, String charset){
        if (!TextUtils.isEmpty(charset)) {
            this.charset = charset;
        }
        StringBuilder contentSb = new StringBuilder();
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()) {
                String name = entry.getKey();
                String value = entry.getValue();
                if (!TextUtils.isEmpty(name) && value != null) {
                    if (contentSb.length() > 0) {
                        contentSb.append("&");
                    }
                    contentSb.append(Uri.encode(name, this.charset))
                            .append("=")
                            .append(Uri.encode(value, this.charset));
                }
            }
        }

        try {
            this.content = contentSb.toString().getBytes(this.charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public long getContentLength() {
        return content.length;
    }

    @Override
    public void setContentType(String contentType) {
    }

    @Override
    public String getContentType() {
        return "application/x-www-form-urlencoded;charset=" + charset;
    }

    @Override
    public void writeTo(OutputStream sink) throws IOException {
        sink.write(this.content);
        sink.flush();
    }
}
